package com.aliengen.thingple.driverapp.service;

import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.activeandroid.ActiveAndroid;
import com.activeandroid.query.Select;
import com.aliengen.thingple.driverapp.data.local.EventModel;
import com.aliengen.thingple.driverapp.data.models.Anomaly;
import com.aliengen.thingple.driverapp.network.api.exception.APICallException;
import com.sdk.bluetooth.android.BluetoothPrinter;

import com.aliengen.thingple.driverapp.network.api.ThingpleAPI;
import com.aliengen.thingple.driverapp.network.volley.Network;
import com.aliengen.thingple.driverapp.data.local.Preferences;
import com.aliengen.thingple.driverapp.device.CMCHandler;

import org.json.JSONObject;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class HandsetApplication extends Application {
    Intent serviceIntent;
    public boolean bBind = false;

    protected Preferences preferences;

    public ThingpleService mService;
    protected Network network;
    public CMCHandler handler = null;
    public ThingpleAPI api = null;

    public CMCHandler getHandler()
    {
        return this.handler;
    }

    public void setHandler(CMCHandler handler) {
        this.handler = handler;
        if(mService != null && mService.device != null)
        {
            mService.device.setHandler(handler);
        }
    }

    public void update()
    {
        AsyncUpdater updater = new AsyncUpdater();
        updater.setApplication(this);
        updater.execute();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getPreferences();
        startService();
        network = getNetwork();
        this.api = new ThingpleAPI(network, getApplicationContext());
        ActiveAndroid.initialize(this);
    }

    /**
     * Get the network handler.
     *
     * @return Network
     */
    public Network getNetwork()
    {
        if(network == null){
            network = Network.getInstance(getApplicationContext());
        }
        return network;
    }

    public BluetoothPrinter getPrinter()
    {
        try {
            BluetoothPrinter printer = new BluetoothPrinter("T5");
            printer.setCurrentPrintType(BluetoothPrinter.PrinterType.T5);
            return printer;
        } catch(NullPointerException e) {
            return null;
        }
    }

    /**
     * Get the preferences handler.
     *
     * @return Preferences
     */
    public Preferences getPreferences() {
        if (preferences == null) {
            preferences = Preferences.getInstance(getApplicationContext());
        }
        return preferences;
    }

    /**
     * Service connection.
     */
    public ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("----Service Disconnected----");
            mService.device.onDisconnect();
            bBind = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("----Service Connected!----");
            ThingpleService.ThingpleBinder binder = (ThingpleService.ThingpleBinder)service;
            mService = binder.GetService();

            if(handler == null)
            {
                System.out.println("Error! Handler not set!");
                return;
            }

            mService.SetBinder(getApplicationContext(), handler);
            mService.device.onConnect();
            bBind = true;
        }
    };

    /**
     * Start the service.
     */
    protected void startService()
    {
        System.out.println("Init service...");
        serviceIntent = new Intent(this, ThingpleService.class);
        startService(serviceIntent);
        try{
            bindService(serviceIntent, conn, Service.BIND_AUTO_CREATE);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Kill the service.
     */
    public void killService()
    {
        System.out.println("Killing service...");
        unbindService(conn);
        stopService(serviceIntent);
    }

    /**
     * Reload the service.
     */
    public void restartService()
    {
        System.out.println("Restarting service...");
        killService();
        startService();
    }
}
